
var util = require("util");

var db = require("./db.js");
var config = require("./config.js");
var httpclient = require("./httpclient.js");

var users = {
	sessions: {}
};

users.dump = function() {
	console.log("user sessions dump: %s", JSON.stringify(users.sessions));
};

users.clear = function(uid) {
	delete users.sessions[uid];
	db.exec([util.format("DELETE FROM users WHERE uid=%d", uid)]);
};

users.init = function() {
	//console.log("users.init()");
	
	return new Promise(function(resolve) {
		db.query("SELECT uid,token,expire,name,icon,max_weibo_id,min_weibo_id FROM users").then(function(rows){
			for (let user of rows)
			{
				users.sessions[user.uid] = user;
			}

			resolve();
		}, function(err){
			console.log("user.load() failed, error: %s", JSON.stringify(err));
		});
	});
};

users.save = function(u) {
	//console.log("users.save(%s)", util.inspect(u));
	
	/* 此处可能存在一个潜在的时序问题
	 * 由于
	 */
	users.sessions[u.uid] = u;
	
	let url = ["https://api.weibo.com/2/users/show.json?access_token="+ u.token,
			   "uid="+ u.uid
			  ].join("&");
	httpclient.get(url, function(data){
		let result = JSON.parse(data);
		let user = {
			uid: result.id,
			token: u.token,
			expire: u.expire,
			name: result.screen_name,
			icon: result.profile_image_url,
			max_weibo_id: 0,
			min_weibo_id: 0
		};

		users.sessions[user.uid] = user;

		db.exec([util.format("DELETE FROM users WHERE uid=%d", user.uid),
				 util.format("INSERT INTO users(uid,token,expire,name,icon) VALUES(%d,\"%s\",%d,\"%s\",\"%s\")", 
					user.uid, user.token, user.expire, user.name, user.icon)]);
	});
};

users.get = function(uid) {
	//console.log("users.get(%d)", uid);
	
	if (undefined === uid)
	{
		return undefined;
	}

	let user = users.sessions[uid];
	if (undefined === user)
	{
		return undefined;
	}

	let now = (new Date).getTime();
	if (user.expire <=  now)
	{
		users.clear(uid);
		return undefined;
	}

	return user;
};

users.update = function(user){
	//console.log("users.update(%s)", util.inspect(user));
	
	db.exec([util.format("UPDATE users SET name=\"%s\" AND icon=\"%s\" WHERE uid=%d", user.name, user.icon, user.uid)]);
};

module.exports = users;
